﻿using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using XJay.DB.Model;
using XJay.Scheduler.Common.CustomException;
using XJay.Scheduler.IService;
using XJay.Scheduler.Model.User.Export;
using XJay.Scheduler.Model.User.Import;

namespace XJay.Scheduler.Service
{
    public class UserServer : IUserServer
    {
        private readonly IConfiguration _configuration;
        private readonly ISqlSugarClient _sqlSugarClient;

        public UserServer(IConfiguration configuration, ISqlSugarClient sqlSugarClient)
        {
            _configuration = configuration;
            _sqlSugarClient = sqlSugarClient;
        }
        public async Task<UserDto> LoginAsync(LoginParam param)
        {
            var user = await _sqlSugarClient.Queryable<User>().Where(p=> p.Email == param.Mail && p.Pwd == param.PassWord).FirstAsync();

            if(user==null)
            {
                throw new XJayException("账号或者密码错误");
            }
            //查找角色
            var role = await _sqlSugarClient.Queryable<Permission>().Where(p => p.UID == user.UID).Select(p=>p.RID).FirstAsync();

            // 2. 从 appsettings.json 中读取SecretKey
            var secretKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["JWT:SecretKey"]));

            // 3. 选择加密算法
            var algorithm = SecurityAlgorithms.HmacSha256;

            // 4. 生成Credentials
            var signingCredentials = new SigningCredentials(secretKey, algorithm);

            // 5. 从 appsettings.json 中读取Expires
            var expires = Convert.ToInt32(_configuration["JWT:Expires"]);


            Claim[] claims = new[] {
                            new Claim("UID", user.UID.ToString()),
                            new Claim("UserName", user.UserName),
                            new Claim("Role", role.ToString()),
                            new Claim("Email", user.Email)
                        };

            // 6. 根据以上，生成token
            var token = new JwtSecurityToken(
                _configuration["JWT:Issuer"],     //Issuer
                _configuration["JWT:Audience"],   //Audience
                claims,                          //Claims,
                DateTime.Now,                    //notBefore
                DateTime.Now.AddMinutes(expires),   //expires
                signingCredentials               //Credentials
            );

            // 7. 将token变为string
            var jwtToken = new JwtSecurityTokenHandler().WriteToken(token);

            return new UserDto() { 
                UID = user.UID,
                UserName = user.UserName,
                Role = role,
                Token = jwtToken
            };
        }
    }
}
